package com.strelitzia.filter;

import com.mysql.cj.util.StringUtils;
import com.strelitzia.constant.SessionID;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @author DONG
 * @create 2023/12/13 12:21
 */
@Component
public class CorsFilter implements Filter {
    public static ThreadLocal<Integer> loginUserId = new ThreadLocal<>();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept, X-Requested-With, remember-me");
        loginUserId.set(null);
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(SessionID.LOGIN_USER)) {
                    if(!StringUtils.isNullOrEmpty(cookie.getValue()))
                        loginUserId.set(Integer.valueOf(cookie.getValue()));
                    break;
                }
            }
            if (loginUserId.get() == null) {
                Object attribute = request.getSession().getAttribute(SessionID.LOGIN_USER);
                if (attribute != null) {
                    loginUserId.set((Integer) attribute);
                }
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

}
